<?php

namespace addons\sum\controller;

use addons\sum\service\Wallet as WalletService;
use addons\sum\controller\traits\Util;
use addons\sum\library\easywechatPlus\WechatMiniProgramShop;
use addons\sum\service\user\Coupon as CouponService;
use app\admin\model\sum\data\Area as AreaModel;
use app\admin\model\sum\decorate\Decorate;
use app\admin\model\sum\decorate\Page;
use app\admin\model\sum\store\Store;
use app\admin\model\sum\user\WalletLog;
use app\common\library\Sms as Smslib;
use app\admin\model\sum\user\User as UserModel;
use addons\sum\facade\Wechat;
use think\Db;
use think\Hook;

class Index extends Common
{
    use Util;

    protected $noNeedLogin = ['init', 'pageSync', 'page', 'feedback', 'send', 'test','getstoreid','addacticleviews','addshare'];
    protected $noNeedRight = ['*'];

    /**
     * 获取商户
     * @return void
     */
    public function getstoreid()
    {
        $store_id=0;
        $store_list=[];
        $store_ids='';
        $params = $this->request->param();
        if(isset($params['staff_id'])&&$params['staff_id']>0){
            $staff=UserModel::where('id',$params['staff_id'])->where('is_staff',1)->find();
            if($staff){
                $store_id=$staff['store_id'];
            }
            $store_ids=$store_id;
        }else{
            $province = AreaModel::where([
                'name' => $params['province_name'],
                'level' => 'province'
            ])->find();
            if (!$province) $this->error('请选择正确的行政区');
            $map['province_id'] = $province->id;
            $city = AreaModel::where([
                'name' => $params['city_name'],
                'level' => 'city',
                'pid' => $province->id
            ])->find();
            if (!$city) $this->error('请选择正确的行政区');
            $map['city_id'] = $city->id;

            $store_count=Store::where($map)->count();
//            $store_list=Store::where($map)->select();
            if($store_count>0){
                $store_ids_arr=Store::where($map)->column('id');
                $store_ids=implode(',',$store_ids_arr);
                $store_id=$store_ids_arr[0];
            }
        }

        $return=[];
        $return['store_id']=$store_id;
//        $return['store_list']=$store_list;
        $return['store_ids']=$store_ids;
        $this->success('获取成功',$return);
    }

    public function init()
    {
        $platform = $this->request->header('platform');
        $templateId = $this->request->param('templateId', 0);
        $platformConfig = sum_config("shop.platform.$platform");

        if (empty($platformConfig['status']) || !$platformConfig['status']) {
            $this->error('暂不支持该平台,请前往商城配置启用对应平台');
        }

        $shopConfig = sum_config('shop.basic');
        $langConfig = sum_config('language');

        $data = [
            'app' => [
                'name' => $shopConfig['name'],
                'logo' => $shopConfig['logo'],
                'phone' => $shopConfig['phone'],
                'app_url' => $shopConfig['app_url'],
                'cdnurl' => cdnurl('', true),
                'version' => $shopConfig['version'],
                'user_protocol' => $shopConfig['user_protocol'],
                'privacy_protocol' =>  $shopConfig['privacy_protocol'],
                'about_us' => $shopConfig['about_us'],
                'copyright' => $shopConfig['copyright'],
                'copytime' => $shopConfig['copytime'],
            ],
//            'popupImage' => [
//                'src' => $shopConfig['popupImage']['src'],
//                'url' => $shopConfig['popupImage']['url'],
//                'show' => $shopConfig['popupImage']['show'],
//            ],
            'language'=>$langConfig,
            'platform' => [
                'auto_login' => $platformConfig['auto_login'] ?? 0,
                'bind_mobile' => $platformConfig['bind_mobile'] ?? 0,
                'payment' => $platformConfig['payment']['methods'],
                'recharge_payment' => sheep_config('shop.recharge_withdraw.recharge.methods'),      // 充值支持的支付方式
                'share' => $platformConfig['share'],
            ],
        ];


        $this->success('初始化', $data);
    }

    public function pageSync()
    {
        $pages = $this->request->post('pages/a');
        foreach ($pages as $page) {
            if (!empty($page['meta']['sync']) && $page['meta']['sync']) {
                $data = \app\admin\model\sum\data\Page::getByPath($page['path']);
                $name = $page['meta']['title'] ?? '未命名';
                $group = $page['meta']['group'] ?? '其它';
                if ($data) {
                    $data->name = $name;
                    $data->group = $group;
                    $data->save();
                } else {
                    \app\admin\model\sum\data\Page::create([
                        'name' => $name,
                        'group' => $group,
                        'path' => $page['path']
                    ]);
                }
            }
        }
        $this->success();
    }

    public function page()
    {
        $id = $this->request->param('id');

        $template = \app\admin\model\sum\decorate\Decorate::typeDiypage()->with('diypage')->where('id', $id)->find();
        if (!$template) {
            $this->error(__('No Results were found'));
        }

        $this->success('', $template);
    }

    public function test()
    {
        $user = UserModel::getByEmail("38577145@qq.com");


//        $user = auth_user();
//
//        $verification=$user['verification'];
//
//        $verification_string = json_encode($verification);
//        $verification_array = json_decode($verification_string, true);
//
//        $return['test']='测试发放佣金';
//        $return['user']=$user;
//        $return['verification']=$verification_array;
//        $return['mobile']=$verification_array['mobile'];
        $this->success('测试什么功能', $user);
    }
    public function test2()
    {
        $user = auth_user();
        $res=CouponService::shopping_give($user);
        $return['res']=$res;
        $return['test']='测试赠送优惠券';
        $this->success('测试什么功能', $return);
    }

    public function feedback()
    {
        $user = auth_user();
        $params = $this->request->only(['type', 'content', 'images', 'phone','contact']);
        if ($user) {
            $params['user_id'] = $user->id;
        }
        $result = \app\admin\model\sum\Feedback::create($params);
        if ($result) {
            $this->success('感谢您的反馈');
        }
    }



    /**
     * 发送验证码
     *
     * @param string $mobile 手机号
     * @param string $event 事件名称
     */
    public function send()
    {
        $mobile = $this->request->post("mobile");
        $event = $this->request->post("event");
        $event = $event ? strtolower($event) : 'register';

        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }

        $last = Smslib::get($mobile, $event);
        if ($last && time() - $last['createtime'] < 60) {
            $this->error(__('发送频繁'));
        }
        $ipSendTotal = \app\common\model\Sms::where(['ip' => $this->request->ip()])->whereTime('createtime', '-1 hours')->count();
        if ($ipSendTotal >= 5) {
            $this->error(__('发送频繁'));
        }
        if ($event) {
            $userinfo = UserModel::getByMobile($mobile);
            if ($event == 'register' && $userinfo) {
                //已被注册
                $this->error(__('手机号已经被注册'));
            } elseif (in_array($event, ['changemobile']) && $userinfo) {
                //被占用
                $this->error(__('手机号已经被占用'));
            } elseif (in_array($event, ['changepwd', 'resetpwd', 'mobilelogin']) && !$userinfo) {
                //未注册
                $this->error(__('手机号未注册'));
            }
        }
        if (!Hook::get('sms_send')) {
            $this->error(__('请在后台插件管理安装短信验证插件'));
        }
        if(config('app_debug_sms')){
            $code='1234';
        }else{
            $code=null;
        }
        $ret = Smslib::send($mobile, $code, $event);
        if ($ret) {
            if(config('app_debug_sms')){
                $this->success(__('发送成功-验证码为1234-仅测试'));
            }else{
                $this->success(__('发送成功'));
            }

        } else {
            $this->error(__('发送失败，请检查短信配置是否正确'));
        }
    }


    /**
     * 获取统一验证 token
     *
     * @return void
     */
    public function unifiedToken()
    {
        $user = auth_user();

        $token = $this->getUnifiedToken('user:' . $user->id);

        $this->success('获取成功', [
            'token' => $token
        ]);
    }

    public function addacticleviews()
    {
        Db::name('config')->where('name','totalacticleviews')->setInc('value');
        $this->success('成功');
    }
    public function addshare()
    {
        Db::name('config')->where('name','totalshare')->setInc('value');
        $this->success('成功');
    }

    /**
     * 每日签到送积分
     * @return void
     */
    public function loginScore(){
        // 改成任务形式
        $user = auth_user();
        // 触发任务事件-点赞视频
        $data = ['event' => 'task_login', 'user' => $user];
        \think\Hook::listen('task_event', $data);

//        $user = auth_user();
//        $today_date=strtotime('today');
//        // 今日送积分记录
//        $user_wallet_log=WalletLog::where('user_id',$user['id'])->where('type','score')->where('createtime','>=',$today_date)->where('event','login')->find();
//        if($user_wallet_log){
//            $this->error(__('今日已赠送'));
//        }
//        $login_score=sum_config('shop.basic.login_score');
//        if($login_score>0){
//            WalletService::change($user, 'score', $login_score, 'login');
//        }
        $this->success(__("操作成功"));
    }

}
